package com.device.auth.controller;


import cn.hutool.json.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/sys/api")
public class DeviceApiController {

    @Autowired
    private MqttClientUtil mqttClientConfig;

    @Autowired
    private PudongDeviceConfigMapper pudongDeviceConfigMapper;

    @PostMapping("/device/auth")
    public JSONObject deviceAuth(@RequestBody JSONObject message){
        JSONObject result =new  JSONObject();
        Object childId = message.get("clientid");
        Object username = message.get("username");
        Object password = message.get("password");
        log.info("尝试连接:"+message);
        if (childId.equals(mqttClientConfig.getClientId())&&username.equals(mqttClientConfig.getUsername())&&password.equals(mqttClientConfig.getPassword()))
        {
            result.set("result", "allow");
//            log.info("管理员登录");
            return result;
        }
//        log.info("设备连接连接ID#{}",childId);
        List<PudongDeviceConfig> deviceNo = pudongDeviceConfigMapper.selectList(new QueryWrapper<PudongDeviceConfig>().eq("device_no", childId));
        if (deviceNo.size()==0){
            log.error("查无device_no");
            result.set("result", "ignore");
            return result;
        }
        PudongDeviceConfig pudongDeviceConfig = deviceNo.get(0);
//        pudongDeviceConfigMapper.selectList(new QueryWrapper<PudongDeviceConfig>().eq("device_no", childId));
        boolean isChildId =pudongDeviceConfig!=null;
        String md5Encode ="";
        StringBuilder sb = new StringBuilder();
        sb.append(childId).append(username);
        if (isChildId) {
            md5Encode=  MD5Util.MD5Encode(sb.toString(), null);
        }
        boolean  isUsername = username.equals(pudongDeviceConfig.getImei());
        boolean isPassword =  password.equals(md5Encode);
        if (isChildId && isPassword && isUsername) {
            result.set("result", "allow");
        }else {
            log.info("ID:#{},密码#{},username:#{}",isChildId,isPassword,isUsername);
            result.set("result", "ignore");
        }
        return result;

    }



}
